package com.cy.dda.web.admin.diligencing;

import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.comm.utils.ExportExcelUtils;
import com.cy.dda.model.PageBean;
import com.cy.dda.model.Result;
import com.cy.dda.model.ao.diligencing.DiligencingEditAO;
import com.cy.dda.model.ao.diligencing.DiligencingReportAuditAO;
import com.cy.dda.model.dto.comm.OSSFileDownloadDTO;
import com.cy.dda.model.dto.diligencing.DiligencingAdminListExportDTO;
import com.cy.dda.model.dto.diligencing.DiligencingImportDTO;
import com.cy.dda.model.query.diligencing.DiligencingAdminListQuery;
import com.cy.dda.model.vo.diligencing.DiligencingAdminDetailVO;
import com.cy.dda.model.vo.diligencing.DiligencingAdminListVO;
import com.cy.dda.service.comm.FileDownloadService;
import com.cy.dda.service.diligencing.DiligencingService;
import com.cy.dda.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @Description 后台-客户尽调管理
 * @Author tanyilin
 * @Date 2019/5/30 10:33
 */
@Slf4j
@RestController
@RequestMapping("/admin/diligencing")
@Api(tags = "后台-客户尽调管理")
public class AdminDiligencingController extends BaseController {

    @Autowired
    private DiligencingService  diligencingService;
    @Autowired
    private FileDownloadService fileDownloadService;

    @ApiOperation("导入尽调案件")
    @PostMapping("/import/excel")
    public Result improtExcel(@RequestParam(value = "file") MultipartFile file){
        //解析Excel表格数据
        List<DiligencingImportDTO> diligencingImportList = diligencingService.getDiligencingImportDTO(file);
        if(CommonUtils.isEmpty(diligencingImportList)) {
            return fail("表格数据为空");
        }
        //添加保存尽调案件数据
        diligencingService.addDiligencings(diligencingImportList);

        return ok("导入尽调案件成功", diligencingImportList);
    }

    @ApiOperation("指定分配")
    @PostMapping("/do/appoint/distribute")
    public Result appointDistribute(@RequestParam(value = "diligencingId") Long diligencingId, @RequestParam(value = "userId") Long userId) {
        diligencingService.appointDistributeDiligencing(diligencingId, userId);
        return ok();
    }

    @ApiOperation("‘未完成’尽调列表")
    @GetMapping("/get/uncompleted/list")
    public PageBean<DiligencingAdminListVO> getUncompletedList(DiligencingAdminListQuery query) {
        query.setFlag(1);
        PageBean<DiligencingAdminListVO> pageBean = diligencingService.selectDiligencingAdminList(query);
        return pageBean;
    }

    @ApiOperation("‘待确认’尽调列表")
    @GetMapping("/get/confirmWait/list")
    public PageBean<DiligencingAdminListVO> getConfirmWaitList(DiligencingAdminListQuery query) {
        query.setFlag(2);
        PageBean<DiligencingAdminListVO> pageBean = diligencingService.selectDiligencingAdminList(query);
        return pageBean;
    }

    @ApiOperation("‘已完成’尽调列表")
    @GetMapping("/get/completed/list")
    public PageBean<DiligencingAdminListVO> getCompletedList(DiligencingAdminListQuery query) {
        query.setFlag(3);
        PageBean<DiligencingAdminListVO> pageBean = diligencingService.selectDiligencingAdminList(query);
        return pageBean;
    }

    @ApiOperation("尽调案件-详情")
    @GetMapping("/get/detail")
    public Result<DiligencingAdminDetailVO> getDiligencingAdminDetail(@RequestParam(value = "diligencingId") Long diligencingId) {

        DiligencingAdminDetailVO detailVO = diligencingService.getDiligencingAdminDetail(diligencingId);
        return ok("获取尽调案件详情成功", detailVO);
    }

    @ApiOperation("尽调案件-编辑")
    @PostMapping("/do/edit")
    public Result doEdit(@Validated DiligencingEditAO editAO, BindingResult bindingResult) {

        this.checkError(bindingResult);
        diligencingService.doEditDiligencing(editAO);
        return ok();
    }

    @ApiOperation("审核尽调报告")
    @PostMapping("/do/audit/report")
    public Result doAuditReport(@Validated DiligencingReportAuditAO auditAO, BindingResult bindingResult) {

        this.checkError(bindingResult);
        diligencingService.doAuditDiligencingReport(auditAO, this.getManager().getManagerId());
        return ok();
    }

    @ApiOperation("导出已完成尽调列表")
    @GetMapping("/completed/list/export")
    public void completedListExport(DiligencingAdminListQuery query, HttpServletRequest req, HttpServletResponse resp) {

        List<DiligencingAdminListExportDTO> data = diligencingService.getDiligencingAdminListExport(query);
        String title = "已完成尽调列表";
        String[] headers = {"案件机构", "客户", "手机号", "类型", "单位名称", "单位地址", "尽调结果",
                "尽调情况", "结论说明", "产品", "更新时间"};
        String[] fieldNames = {"orgName", "customerName", "mobile", "customerType", "companyName", "companyAddress", "diligencingResultText",
                "diligencingSituation", "diligencingResultDesc", "productName", "updateTime"};
        ExportExcelUtils<DiligencingAdminListExportDTO> ex = new ExportExcelUtils<>();
        try(OutputStream out = resp.getOutputStream()) {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/x-download");
            String fileName = CommonUtils.getCurrentTimeAndRandomNumber().concat(".xls");
            fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ex.exportExcel(title, headers, fieldNames, data, out);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @ApiOperation("一键下载")
    @GetMapping("/download/zip")
    public void downloadFilesForZip(HttpServletResponse response, @RequestParam(value = "diligencingId") Long diligencingId) {

        //查询并封装好需要下载的文件数组
        List<OSSFileDownloadDTO> list = diligencingService.getOSSFileDownloadDTO(diligencingId);
        try {
            response.setContentType("application/doc");
            response.addHeader("Content-Disposition", "attachment;filename=attachment-" + diligencingId + ".zip");
            //缓冲文件输出流
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            fileDownloadService.downloadFilesForZip(list, bos);

        } catch (IOException e) {
            log.error("downloadFilesForZip error", e);
        }
    }



}
